package org.zyj.io.protocal.replaying;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.zyj.io.protocal.Message;

import javax.net.ssl.SSLException;
import java.nio.charset.StandardCharsets;

public class Client {

    static final String HOST = "127.0.0.1";
    static final int PORT = 9998;
    static final int SIZE = 256;

    public static void main(String[] args) throws SSLException, InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new MessageEncoder()) //把java对象转化成ByteBuf
                                    .addLast(new ClientHandler()) //
                            ;
                        }
                    });
            ChannelFuture f = b.connect(HOST, PORT).sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    private static class ClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            //建立连接的时候就发一条数据
            Message message = new Message();
            message.setVersion(1);
            message.setOpCode(2);
            message.setStreamId(3);
            byte[] bytes = "ReplayingDecoder的使用示例".getBytes(StandardCharsets.UTF_8);
            message.setBody(bytes);
            //出站
            ctx.writeAndFlush(message);
            ctx.writeAndFlush(message);
        }
    }
}
